<script>
export default {
  name: 'CountBox',
  props: {
    value: {
      tye: Number,
      default: 1
    }
  },
  methods: {
    handleSub () {
      if (this.value <= 1) {
        return
      }
      this.$emit('input', this.value - 1)
    },
    handleAdd () {
      this.$emit('input', this.value + 1)
    },
    handleChange (e) {
      // console.log(e.target.value)
      const num = +e.target.value
      if (isNaN(num) || num < 1) {
        // 输入了不合法的文本/输入负值，回退成原来的数字
        e.target.value = this.value
        return
      }
      this.$emit('input', num)
    }
  }
}
</script>

<template>
  <div class="count-box">
    <button class="minus" @click="handleSub">-</button>
    <input :value="value" class="inp" type="text" @change="handleChange">
    <button class="add" @click="handleAdd">+</button>
  </div>
</template>

<style scoped lang="less">
.count-box {
  width: 110px;
  display: flex;

  .add, .minus {
    width: 30px;
    height: 30px;
    outline: none;
    border: none;
    background-color: #efefef;
  }

  .inp {
    width: 40px;
    height: 30px;
    outline: none;
    border: none;
    margin: 0 5px;
    background-color: #efefef;
    text-align: center;
  }
}
</style>
